package qj.util.io;

import java.io.IOException;
import java.io.InputStream;

public class ConvertTo8BitsInputStream extends InputStream {
	
	private final InputStream in;

	public ConvertTo8BitsInputStream(InputStream in) {
		this.in = in;
	}

	private int index = 0;
	private byte[] buffer = new byte[7];
	private int read = 0;
	public int read() throws IOException {
		if (index>=read) {
			index = 0;
			readMore();
		}
		if (read>-1)
			return toInt(buffer[index++]);
		else
			return -1;
	}

	private int toInt(byte b) {
		if (b<0)
			return b+256;
		else
			return b;
	}

	private byte[] buffer2 = new byte[8];
	private void readMore() throws IOException {
        int read;
        if ((read = in.read(buffer2, 0, 8)) > -1) {
        	convertTo8Bits(buffer2, read);
        	for (int i = 1; i < read; i++) {
        		buffer[i - 1] = buffer2[i];
			}
            this.read = read - 1;
        } else {
            this.read = -1;
        }
	}

	private static void convertTo8Bits(byte[] buffer, int read) {
		for (int i = 1; i < read; i++) {
			if ((byte)(buffer[0]/Math.pow(2, 7-i)) % 2==1)
				buffer[i] -= 128;
		}
	}

	public void close() throws IOException {
		if (in!=null)
			in.close();
	}
	
}
